<template>
	<div>
		<el-form :inline="true">
			<el-form-item>
				<el-input
						v-model="searchForm.buyName"
						placeholder="商品名称"
						clearable
						style="margin-right:10px; width:30%"
				>
				</el-input>

				<el-input
						v-model="searchForm.type"
						placeholder="类别"
						clearable
						style="margin-right:10px; width:30%"
				>
				</el-input>
			</el-form-item>

			<el-form-item>
				<el-button @click="getBuyList">搜索</el-button>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="addHandle" v-if="hasAuth('sys:buy:save')">购买商品</el-button>
			</el-form-item>
			<el-form-item>
				<el-popconfirm title="确定批量删除吗？" @confirm="delHandle(null)">
					<el-button type="danger" slot="reference" v-if="hasAuth('sys:buy:delete')">批量删除</el-button>
				</el-popconfirm>
			</el-form-item>
		</el-form>

		<el-table
				ref="multipleTable"
				:data="tableData"
				tooltip-effect="dark"
				style="width: 100%"
				border
				stripe
				@selection-change="handleSelectionChange">

			<el-table-column
					type="selection"
					width="55">
			</el-table-column>

			<el-table-column
					prop="goodsName"
					label="商品名称"
					width="120">
			</el-table-column>

			<el-table-column
					prop="type"
					label="类别">
			</el-table-column>

			<el-table-column
					prop="price"
					label="价格">
			</el-table-column>

			<el-table-column
					prop="goodsNum"
					label="购买数量">
			</el-table-column>

			<el-table-column
					prop="created"
					width="200"
					label="购买时间"
					:formatter="formatDateTime"
			>
			</el-table-column>

			<el-table-column
					prop="updated"
					width="200"
					label="修改时间"
					:formatter="formatDateTime"
			>
			</el-table-column>

			<el-table-column
					prop="icon"
					width="200px"
					label="操作">

				<template slot-scope="scope">
					<el-button type="text" @click="editHandle(scope.row.id)"  v-if="hasAuth('sys:buy:update')">编辑</el-button>
					<el-divider direction="vertical" v-if="hasAuth('sys:buy:update')"></el-divider>

					<template>
						<el-popconfirm title="确定删除这个商品吗？" @confirm="delHandle(scope.row.id)">
							<el-button type="text" slot="reference"  v-if="hasAuth('sys:buy:delete')">删除</el-button>
						</el-popconfirm>
					</template>
				</template>
			</el-table-column>

		</el-table>

		<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100]"
				:current-page="current"
				:page-size="size"
				:total="total">
		</el-pagination>


		<!--新增对话框-->
		<el-dialog
				title="提示"
				:visible.sync="dialogVisible"
				width="600px"
				:before-close="handleClose">

			<el-form :model="editForm" :rules="editFormRules" ref="editForm">
				<el-form-item label="商品"  prop="goodsId" label-width="100px">
					<el-select v-model="editForm.goodsId" placeholder="请选择商品" style="width:400px">
					<el-option
					v-for="item in goodsOptions"
					:key="item.id"
					:label="item.goodsName + '      价格:' + item.price + '        库存:' + item.number"
					:value="item.id">
					</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="数量" prop="goodsNum" label-width="100px">
					<el-input v-model="editForm.goodsNum" autocomplete="off"></el-input>
				</el-form-item>
=
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetForm('editForm')">取 消</el-button>
				<el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	var padDate = function (value) {
		return value <10 ? '0' + value:value;
	};
	export default {
		name: "Buy",
		data() {
			return {
				searchForm: {},
				delBtlStatu: true,

				total: 0,
				size: 10,
				current: 1,

				dialogVisible: false,
				editForm: {

				},

				tableData: [],

				editFormRules: {
					goodsId: [
						{required: true, message: '请选择商品', trigger: 'blur'}
					],
					goodsNum: [
						{required: true, message: '请输入商品数量', trigger: 'blur'}
					],
				},

				multipleSelection: [],

				roleDialogFormVisible: false,
				defaultProps: {
					children: 'children',
					label: 'name'
				},
				buyData:  [],
				treeCheckedKeys: [],
				checkStrictly: true,
				goodsOptions: [
				],
				userInfo: {
					id: "",
					username: "",
					avatar: ""
				},
				userId: '',
			}
		},
		created() {
			this.getBuyList()
			this.getGoodsList()
			this.$axios.get("/sys/buy/list").then(res => {
				this.buyData = res.data.data.records
			})
		},
		methods: {
			toggleSelection(rows) {
				if (rows) {
					rows.forEach(row => {
						this.$refs.multipleTable.toggleRowSelection(row);
					});
				} else {
					this.$refs.multipleTable.clearSelection();
				}
			},
			handleSelectionChange(val) {
				console.log("勾选")
				console.log(val)
				this.multipleSelection = val;

				this.delBtlStatu = val.length == 0
			},

			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.size = val
				this.getBuyList()
			},
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.current = val
				this.getBuyList()
			},

			resetForm(formName) {
				this.$refs[formName].resetFields();
				this.dialogVisible = false
				this.editForm = {}
			},
			handleClose() {
				this.resetForm('editForm')
			},

			getBuyList() {
				this.$axios.get("/sys/buy/findBuyList", {
					params: {
						goodsName: this.searchForm.goodsName,
						type: this.searchForm.type,
						userId: this.userId,
						current: this.current,
						size: this.size
					}
				}).then(res => {
					this.tableData = res.data.data.records
					this.size = res.data.data.size
					this.current = res.data.data.current
					this.total = res.data.data.total
				})
			},

			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.$axios.post('/sys/buy/' + (this.editForm.id?'update' : 'save'), this.editForm)
							.then(res => {

								this.$message({
									showClose: true,
									message: '恭喜你，操作成功',
									type: 'success',
									onClose:() => {
										this.getBuyList()
									}
								});

								this.dialogVisible = false
							})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			editHandle(id) {
				this.$axios.get('/sys/buy/info/' + id).then(res => {
					this.editForm = res.data.data
					this.dialogVisible = true
				})
			},
			addHandle() {
				this.editForm = {}
				this.dialogVisible = true
			},
			delHandle(id) {

				var ids = []

				if (id) {
					ids.push(id)
				} else {
					this.multipleSelection.forEach(row => {
						ids.push(row.id)
					})
				}

				console.log(ids)

				this.$axios.post("/sys/buy/delete", ids).then(res => {
					this.$message({
						showClose: true,
						message: '恭喜你，操作成功',
						type: 'success',
						onClose:() => {
							this.getBuyList()
						}
					});
				})
			},
			
			// 时间格式方法
			formatDateTime(row, column) {
				// 获取单元格数据
				let data = row[column.property]
				if(data == null) {
					return null
				}
				let dt = new Date(data)
				return dt.getFullYear() + '-' + padDate(dt.getMonth() + 1) + '-' + padDate(dt.getDate()) + ' ' + padDate(dt.getHours()) + ':' + padDate(dt.getMinutes()) + ':' + padDate(dt.getSeconds())
			},
			// 日期格式方法
			formatDate(row, column) {
				// 获取单元格数据
				let data = row[column.property]
				if(data == null) {
					return null
				}
				let dt = new Date(data)
				return dt.getFullYear() + '-' + padDate(dt.getMonth() + 1) + '-' + padDate(dt.getDate())
			},
			getGoodsList(){
				this.$axios.get("/sys/goods/findAllList").then(res => {
				this.goodsOptions = res.data.data
				})
			},
			getUserInfo() {
				this.$axios.get("/sys/userInfo").then(res => {
					this.userInfo = res.data.data
					this.editForm.userId = this.userInfo.id
					this.userId = this.userInfo.id
				})
			},
			
		}
	}
</script>

<style scoped>

	.el-pagination {
		float: right;
		margin-top: 22px;
	}

</style>